﻿using RankDemo.WebApi.Entities;

namespace RankDemo.WebApi.Services
{
    public interface IRankService
    {
        void CreateCustomer(Customer customer);
        void UpdateCustomerScore(Customer customer, int score);
        List<Leaderboard> GetAll();
    }

    public class RankService : IRankService
    {
        private static readonly RankBinaryTree _rankBinaryTree = new RankBinaryTree(1000000);

        public void CreateCustomer(Customer customer)
        {
            _rankBinaryTree.Insert(customer.Score, customer.CustomerId);
        }

        public List<Leaderboard> GetAll()
        {
            var rankDictionary = _rankBinaryTree.GetAllLeaf();
            return rankDictionary;
        }

        public void UpdateCustomerScore(Customer customer, int score)
        {
            var originScore = customer.Score;
            customer.ChangeScore(score);

            if (customer.IsDefaultScoreValue())
            {
                _rankBinaryTree.Remove(originScore, customer.CustomerId);
            }
            else
            {
                _rankBinaryTree.Update(originScore, customer.Score, customer.CustomerId);
            }
        }
    }
}
